package com.cheng.operation.impl;

import com.cheng.common.exception.CommonException;
import com.cheng.common.utils.*;
import com.cheng.data.entity.BorrowInfoEntity;
import com.cheng.data.entity.CompanyInfoEntity;
import com.cheng.data.vo.*;
import com.cheng.operation.ArchiveTypeInfOperation;
import com.cheng.operation.BorrowOperation;
import com.cheng.operation.GvmtTypeInfOperation;
import com.cheng.service.BorrowService;
import com.cheng.service.CompanyInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author: ChengJW
 * @date: 2021/12/20 20:17
 * @version: 1.0
 * @description: 借阅信息处理类
 */
@Service
public class BorrowOperationImpl implements BorrowOperation {

    private final static Logger log = LoggerFactory.getLogger(BorrowOperationImpl.class);

    @Autowired
    private BorrowService borrowService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private ArchiveTypeInfOperation archiveTypeInfOperation;

    @Autowired
    private GvmtTypeInfOperation gvmtTypeInfOperation;

    /**
     * @author: ChengJW
     * @params: [entity]
     * @return: void
     * @date: 2021/12/20
     * @description: 新增借阅信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertBorrowInfo(BorrowInfoVO borrowInfoVO) throws CommonException {
        if (borrowInfoVO == null){
            log.error("借阅信息为空，无法进行下一步操作");
            throw new CommonException("CJW202111010057","BorrowOperationImpl","insertBorrowInfo");
        }
        if (CodeUtil.BROW_TYPE_STD_0.equals(borrowInfoVO.getBwType())) {
            BorrowInfoEntity entity = new BorrowInfoEntity();
            BeanUtils.copyProperties(borrowInfoVO, entity);
            entity.setBwId(IdUtil.getBrowId());
            entity.setStDt(new Date());
            entity.setUtDt(new Date());
            entity.setBwCd(CodeUtil.READ_STD_1);
            //由于 档案核准日期，出借日期、归还日期 VO 和 entity 的格式不一致，所以需要单独 set 值
            entity.setBwCmCheckDt(DateUtil.strToDate(borrowInfoVO.getBwCmCheckDt(),CodeUtil.DATE_STRING));
            entity.setBwReadDt(DateUtil.strToDate(borrowInfoVO.getBwReadDt(),CodeUtil.DATE_STRING));
            entity.setBwDt(DateUtil.strToDate(borrowInfoVO.getBwDt(),CodeUtil.DATE_STRING));
            borrowService.insertBorrowInfo(entity);

            //修改 company_info 的借阅标志
            CompanyInfoVO vo = new CompanyInfoVO();
            vo.setCiBussId(borrowInfoVO.getBwBussId());
            CompanyInfoEntity infoEntity = companyInfoService.queryCompanyInfoList(vo);
            infoEntity.setCiBrowCd(CodeUtil.READ_STD_1);
            infoEntity.setUtDt(new Date());
            companyInfoService.updateCompanyInfo(infoEntity);
        }else {
            String cmCreditCode = borrowInfoVO.getBwCmCreditCode();
            //通过 统一社会信用代码 查询 company_info 表里的 所有该户企业信息
            Map<String,Object> map = new HashMap<>();
            map.put("ci_Credit_Code",borrowInfoVO.getBwCmCreditCode());
            List<CompanyInfoEntity> list = companyInfoService.queryCompanyInfoList(map);
            if (list != null && list.size() > 0){
                for (CompanyInfoEntity entity : list){

                    //对查出的档案卷信息进行判断，如果已经借出，则该档案不能继续借出
                    if (CodeUtil.READ_STD_1.equals(entity.getCiBrowCd())){
                        continue;
                    }
                    entity.setUtDt(new Date());
                    entity.setCiBrowCd(CodeUtil.READ_STD_1);
                    companyInfoService.updateCompanyInfo(entity);

                    //插入 borrow_info 信息
                    BorrowInfoEntity borrowInfoEntity = new BorrowInfoEntity();
                    borrowInfoEntity.setBwId(IdUtil.getBrowId());
                    borrowInfoEntity.setBwBussId(entity.getCiBussId());
                    borrowInfoEntity.setBwCmRegistId(entity.getCiRegistId());
                    borrowInfoEntity.setBwCmNm(entity.getCiNm());
                    borrowInfoEntity.setBwCmCreditCode(entity.getCiCreditCode());
                    borrowInfoEntity.setBwCmArchType(archiveTypeInfOperation.queryArchiveTypeInfNmByCode(entity.getCiArchTpye()));
                    borrowInfoEntity.setBwCmCheckDt(entity.getCiCheckDt());
                    borrowInfoEntity.setBwCmTotalNum(entity.getCiAresTolNum());
                    //出借人账号
                    borrowInfoEntity.setBwNm(borrowInfoVO.getBwNm());
                    //出借人姓名
                    borrowInfoEntity.setBwRealNm(borrowInfoVO.getBwRealNm());
                    //借阅人
                    borrowInfoEntity.setBwReadNm(borrowInfoVO.getBwReadNm());
                    borrowInfoEntity.setBwCode(borrowInfoVO.getBwCode());
                    //出借日期 string -> date 进行转换
                    borrowInfoEntity.setBwDt(DateUtil.strToDate(borrowInfoVO.getBwDt(),CodeUtil.DATE_STRING));
                    borrowInfoEntity.setBwReadDt(DateUtil.strToDate(borrowInfoVO.getBwReadDt(),CodeUtil.DATE_STRING));
                    borrowInfoEntity.setBwCd(CodeUtil.READ_STD_1);
                    borrowInfoEntity.setBwDesc(borrowInfoVO.getBwDesc());
                    borrowInfoEntity.setStDt(new Date());
                    borrowInfoEntity.setUtDt(new Date());
                    borrowService.insertBorrowInfo(borrowInfoEntity);
                }
            }
        }
    }

    /**
     * @author: ChengJW
     * @params: [map]
     * @return: java.util.List<com.cheng.data.vo.BorrowInfoVO>
     * @date: 2021/12/20
     * @description: 查询待归还的借阅信息
     */
    @Override
    public RespPageInfoVO queryBorrowInfoList(ReqPageInfoVO vo) throws CommonException {
        if (null == vo){
            log.error("查询条件信息为空，无法进行下一步操作");
            throw new CommonException("CJW202111010054","CompanyInfoOperationImpl","queryCompanyInfoVOList");
        }
        Map<String,Object> map = new HashMap<>();
        map.put(CodeUtil.SRCH_REQ_FIR,vo.getSrchReqFir());
        if (StringUtil.isNotNull(String.valueOf(vo.getQryReqFir()))){
            map.put(CodeUtil.QRY_REQ_FIR,"%"+vo.getQryReqFir()+"%");
        }
        map.put(CodeUtil.USER_CODE,vo.getUserCode());
        PageInfo<CompanyInfoVO> pageInfo = PageHelper.startPage(vo.getPageNum(),vo.getPageSize()).doSelectPageInfo(() -> borrowService.queryBorowInfoList(map));
        return RespUtils.respPageInfoVO(pageInfo);
    }

    /**
     * @author: ChengJW
     * @params: [bwBussList,userNm]
     * @return: void
     * @date: 2021/12/20
     * @description: 修改借阅信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBorrowInfo(List<String> bwIdList,String userNm) throws CommonException {

        if (bwIdList == null || bwIdList.size() == 0){
            log.error("查询条件信息为空，无法进行下一步操作");
            throw new CommonException("CJW202111010054","CompanyInfoOperationImpl","updateBorrowInfo");
        }
        for (String bwId : bwIdList){
            BorrowInfoVO borrowInfoVO = new BorrowInfoVO();
            borrowInfoVO.setBwId(bwId);
            BorrowInfoEntity entity = borrowService.queryBorrowInfo(borrowInfoVO);
            entity.setUtDt(new Date());
            entity.setBwCd(CodeUtil.READ_STD_0);
            entity.setBwAceptNm(userNm);
            entity.setBwAceptDt(new Date());
            borrowService.updateBorrowInfo(entity);

            //修改 company_info
            CompanyInfoVO companyInfoVO = new CompanyInfoVO();
            companyInfoVO.setCiBussId(entity.getBwBussId());
            CompanyInfoEntity companyInfoEntity = companyInfoService.queryCompanyInfoList(companyInfoVO);
            companyInfoEntity.setUtDt(new Date());
            companyInfoEntity.setCiBrowCd(CodeUtil.READ_STD_0);
            companyInfoService.updateCompanyInfo(companyInfoEntity);
        }
    }

    /**
     * @author: ChengJW
     * @params: [vo]
     * @return: com.cheng.data.vo.RespPageInfoVO
     * @date: 2021/12/21
     * @description: 统计借阅信息数据
     */
    @Override
    public RespPageInfoVO queryStatisticsBrowVOList(ReqPageInfoVO pageVO) throws CommonException {
        if (pageVO == null || pageVO.getSrchReqFir() == null){
            log.error("查询条件信息为空，无法进行下一步操作");
            throw new CommonException("CJW202111010054","CompanyInfoOperationImpl","queryStatisticsVOList");
        }

        //对查询结果进行分页
        Map<String,Object> map = new HashMap<>();
        map.put(CodeUtil.STATISTIC_CODE,pageVO.getSrchReqFir());
        //开始日期为当天的第一秒
        if (StringUtil.isNotNull(pageVO.getStDt())){
            map.put("stDt",pageVO.getStDt()+" 00:00:00");
        }
        if (StringUtil.isNotNull(pageVO.getLmDt())){
            map.put("lmDt",pageVO.getLmDt()+" 23:59:59");
        }
        PageInfo<StatisticsVO> pageInfo = PageHelper.startPage(pageVO.getPageNum(),pageVO.getPageSize()).doSelectPageInfo(() -> borrowService.queryStatisticsBrowVO(map));
        List<StatisticsVO> list = new ArrayList<>();
        if (pageInfo.getList() != null && pageInfo.getList().size() > 0){
            for (StatisticsVO vo : pageInfo.getList()){
                vo.setMgeNm(gvmtTypeInfOperation.queryGvmtTypeInfNmByCode(vo.getMgeCode()));
                list.add(vo);
            }
        }
        pageInfo.setList(list);
        return RespUtils.respPageInfoVO(pageInfo);
    }

    /**
     * @author: ChengJW
     * @params: [urNm]
     * @return: com.cheng.data.vo.NoticeVO
     * @date: 2021/12/21
     * @description: 查询用户名下待归还企业信息
     */
    @Override
    public NoticeVO queryBorrowInfoNoticeVO(String urNm) throws CommonException {
        Map<String,Object> map = new HashMap<>();
        map.put(CodeUtil.USER_NM,urNm);
        map.put(CodeUtil.NOW_DATE,new Date());
        return borrowService.queryBorrowInfoNoticeVO(map);
    }
}
